/**
 * @module		请求文件
 * @author      nayo
 * @date        2020/9/23 2:43 下午
 * @version     1.0
 */
import axios from 'axios';
import store from '@/store';
import router from '@/router';

let timeNumber401 = new Date().getTime();

export const Request = axios.create({
	baseURL: '/'
});

let errorMessage = (msg) => {
};

Request.interceptors.request.use(
	conf => {
		if (store.getters.token && store.getters.expiresAt > new Date().getTime()) {
			conf.headers['Authorization'] = 'Bearer ' + store.getters.token
		}
		return conf;
	},
	err => {
		return Promise.reject(err);
	}
);

Request.interceptors.response.use(
	response => {
		return response;
	},
	err => {
		let resp = err.response;
		if (!resp) {
			errorMessage(err.message);
			return Promise.reject(err);
		}
		if (resp.config.url.indexOf('/auth/logout') !== -1) {
			return Promise.reject(err);
		}
		switch (resp.status) {
			case 400:
				errorMessage('客户端请求的语法错误，服务器无法理解，Api是:' + resp.config.url);
				break;
			case 404:
				errorMessage('请求资源不存在，Api是：' + resp.config.url);
				break;
			case 405:
				errorMessage('客户端请求中的方法被禁止，Api是：' + resp.config.url);
				break;
			case 401:
				break;
			case 403:
				errorMessage('无权访问：403');
				break;
			case 500:
				errorMessage(resp.data.msg);
				break;
			case 501:
				errorMessage('服务器不支持请求的功能，无法完成请求，Api是：' + resp.config.url);
				break;
			case 502:
				errorMessage('网关错误：502');
				break;
			case 503:
				errorMessage('服务器超载或系统维护');
				break;
		}
		return Promise.reject(err);
	}
);

export default Request;
